// created by anve 2020.10.29
module de_to_fsync(
	input clk,
	input de,
	input rst_n,
	output fsync_out
);

reg fsync_out;

reg [31:0] de_count;
reg [31:0] clk_count;
reg de_d0;
reg de_d1;
reg [3:0] state;

assign de_posedge = (!de_d1)&(de_d0);
assign de_negedge = (de_d1)&(!de_d0);

always @ (posedge clk)
begin
	if(!rst_n) begin
		de_count <= 0;
		clk_count <= 0;
		fsync_out <= 0;
		de_d0 <= 0;
		de_d1 <= 0;
		state <= 0;
	end
	else begin
		de_d0 <= de;
		de_d1 <= de_d0;
		
		case (state)
			0: begin
				if(de_posedge) begin
					clk_count <= 0;
					state <= 1;
				end
				if(de_negedge) begin
					clk_count <= 0;
					state <= 2;
				end
			end
			1: begin
				if(de_negedge) begin
					de_count <= clk_count;
					clk_count <= 0;
					state <= 2;
				end
				else begin
					clk_count <= clk_count+1;
				end
				fsync_out <= 0;
			end
			2: begin
				if(de_posedge) begin
					if((de_count+de_count)<clk_count) begin
						fsync_out <= 1;
					end
					clk_count <= 0;
					state <= 1;
				end
				else begin
					clk_count <= clk_count+1;
				end
			end
			
		endcase
		
		
		
	end

end


endmodule